<template>
  <div class="content-box" style="background-color: #fff">
    <div style="margin-bottom: 10px">
      <h3 align="center">{{ head }}</h3>
      <h3 align="center">
        <hr
          style="
            width: 150px;
            border: none;
            border-top: 6px solid #606266;
            margin-bottom: 3px;
          "
        />
        <hr style="width: 150px; border: none; border-top: 2px solid #606266" />
      </h3>
    </div>
    <div class="container">
      <div class="container1">
        <div>
          <!-- 项目基本信息 -->
          <div style="width: 100%; height: 30px; background-color: #fafafa">
            <!-- 隐藏按钮 -->
            <el-button
              v-if="isDisplay == true"
              icon="el-icon-arrow-up"
              @click="changeDisplay()"
              circle
              size="mini"
              style="color: #7aaafd"
            ></el-button>
            <el-button
              v-else
              @click="changeDisplay()"
              icon="el-icon-arrow-down"
              circle
              size="mini"
              style="color: #7aaafd"
            ></el-button>
            &nbsp;项目基本信息
          </div>
          <div v-show="isDisplay">
            <el-form
              label-width="180px"
              size="mini"
              :label-position="labelPosition"
              style="margin-top: 10px"
              :rules="saveRules"
              :model="saveForm"
              :inline="true"
              ref="saveForm"
            >
              <el-form-item label="项目" prop="projectId">
                <el-select
                  v-model="saveForm.projectId"
                  style="width: 218px"
                  clearable
                >
                  <el-option
                    v-for="item in projectList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="交底日期" prop="dateOfDisclosure">
                <el-date-picker
                  v-model="saveForm.dateOfDisclosure"
                  style="width: 218px"
                  type="date"
                  align="right"
                  placeholder="选择日期"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="交底类型" prop="typeOfDisclosure">
                <el-select
                  v-model="saveForm.typeOfDisclosure"
                  style="width: 218px"
                  clearable
                >
                  <el-option
                    v-for="item in typeOfDisclosureList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="交底人" prop="objectOfDisclosure">
                <el-select
                  v-model="saveForm.objectOfDisclosure"
                  style="width: 218px"
                  clearable
                >
                  <el-option
                    v-for="item in userList"
                    :key="item.id"
                    :label="item.userName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="被交底部门" prop="theInformantDepartment">
                <el-select
                  v-model="saveForm.theInformantDepartment"
                  style="width: 218px"
                  clearable
                >
                  <el-option
                    v-for="item in departmentList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="被交底人" prop="personBeingDisclosed">
                <el-select
                  v-model="saveForm.personBeingDisclosed"
                  style="width: 218px"
                  clearable
                >
                  <el-option
                    v-for="item in userList"
                    :key="item.id"
                    :label="item.userName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="交底内容" prop="contentOfDisclosure">
                <el-input
                  v-model="saveForm.contentOfDisclosure"
                  style="width: 218px"
                ></el-input>
              </el-form-item>
              <el-form-item label="交底资料" prop="disclosureOfInformation">
                <el-input
                  v-model="saveForm.disclosureOfInformation"
                  style="width: 218px"
                ></el-input>
              </el-form-item>
              <el-form-item label="现场照片">
                <el-upload
                  class="upload-demo"
                  :action="' '"
                  accept=".jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG,.PBG,.GIF,.BMP,.PDF"
                  :auto-upload="false"
                  :file-list="HFfileList"
                  :on-remove="HFhandleRemove"
                  :on-change="HFhandleChangeImg"
                >
                  <img
                    :src="hfpng"
                    alt
                    v-if="hfpng || dredgeServe.HFname"
                    style="height: 70px; width: 70px"
                  />
                  <img
                    v-else
                    src="../../assets/logo.png"
                    style="height: 70px; width: 70px"
                    alt
                  />
                </el-upload>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <!-- 附件 -->
        <div>
          <div style="width: 100%; height: 30px; background-color: #fafafa">
            <!-- 隐藏按钮 -->
            <el-button
              v-if="isDisplayFile == true"
              icon="el-icon-arrow-up"
              @click="changeDisplayFile()"
              circle
              size="mini"
              style="color: #7aaafd"
            ></el-button>
            <el-button
              v-else
              @click="changeDisplayFile()"
              icon="el-icon-arrow-down"
              circle
              size="mini"
              style="color: #7aaafd"
            ></el-button>
            &nbsp;附件上传
          </div>
          <div v-show="isDisplayFile">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              >上传</el-button
            >
            <el-table
              :data="attachments"
              border
              height="300"
              style="width: 100%; font-size: 12px; margin-top: 10px"
              :cell-style="cellStyle"
              :header-cell-style="rowClass"
              :show-overflow-tooltip="true"
            >
              <el-table-column
                label="文件名称"
                align="center"
                prop="fileName"
              ></el-table-column>
              <el-table-column
                label="文件类型"
                align="center"
                prop="fileType"
              ></el-table-column>
              <el-table-column
                label="文件大小(MB)"
                align="center"
                prop="fileSize"
              ></el-table-column>
              <el-table-column label="状态" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.state == 0">上传成功</span>
                  <span v-if="scope.row.state == 1">待提交</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <teleport slot-scope="scope">
                  <template>
                    <show v-if="head === '修改项目'">
                      <el-button
                        type="primary"
                        plain
                        icon="el-icon-download"
                        size="mini"
                        @click="download(scope.row)"
                        >下载</el-button
                      >
                    </show>
                    <el-button
                      type="primary"
                      plain
                      icon="el-icon-delete"
                      size="mini"
                      @click="deleteFile(scope.$index, scope.row)"
                      >删除</el-button
                    >
                  </template>
                </teleport>
              </el-table-column>
            </el-table>
          </div>
          <file-upload
            ref="fileUploadDialog"
            @input="getAttachList"
          ></file-upload>
        </div>
      </div>
    </div>
    <div style="text-align: center">
      <!-- 返回上一个页面 -->
      <el-button @click="back()" size="mini">取 消</el-button>
      <el-button type="primary" @click="trueAdd()" size="mini">确 定</el-button>
    </div>
  </div>
</template>

<script>
import sysDialog from "@/components/common/sysDialog.vue"; // 弹窗
import FileUpload from "@/components/common/fileUpload.vue"; // 附件上传
import request from "@/util/request";
import axios from "axios";
const saveForm = {
  //项目基本信息
  projectId: "", //项目
  dateOfDisclosure: "", //交底日期
  typeOfDisclosure: "", //交底类型
  objectOfDisclosure: "", //交底人
  theInformantDepartment: "", //被交底部门
  personBeingDisclosed: "", //被交底人
  contentOfDisclosure: "", //交底内容
  disclosureOfInformation: "", //交底资料
};
const saveRules = {
  //项目基本信息校验规则
  projectId: [
    {
      required: true,
      message: "请选择项目",
      trigger: "change",
    },
  ],
  dateOfDisclosure: [
    {
      required: true,
      message: "请选择交底日期",
      trigger: "change",
    },
  ],
  typeOfDisclosure: [
    {
      required: true,
      message: "请选择交底类型",
      trigger: "change",
    },
  ],
  objectOfDisclosure: [
    {
      required: true,
      message: "请选择交底人",
      trigger: "change",
    },
  ],
  theInformantDepartment: [
    {
      required: true,
      message: "请选择被交底部门",
      trigger: "change",
    },
  ],
  personBeingDisclosed: [
    {
      required: true,
      message: "请选择被交底人",
      trigger: "change",
    },
  ],
  contentOfDisclosure: [
    {
      required: true,
      message: "请输入交底内容",
      trigger: "blur",
    },
  ],
  disclosureOfInformation: [
    {
      required: true,
      message: "请输入交底资料",
      trigger: "blur",
    },
  ],
};
const pickerOptions = {
  // 时间选择器
  /* disabledDate(time) { //禁用时间 不能选今天之后的时间
    return time.getTime() > Date.now();
  }, */
  shortcuts: [
    {
      text: "今天",
      onClick(picker) {
        picker.$emit("pick", new Date());
      },
    },
    {
      text: "昨天",
      onClick(picker) {
        const date = new Date();
        date.setTime(date.getTime() - 3600 * 1000 * 24);
        picker.$emit("pick", date);
      },
    },
    {
      text: "一周前",
      onClick(picker) {
        const date = new Date();
        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
        picker.$emit("pick", date);
      },
    },
  ],
  // disabledDate(time) { //禁用时间 不能选今天之前的时间
  //   const dateTime = new Date();
  //   const startDateTime = dateTime.setDate(dateTime.getDate() - 1);
  //   const endDateTime = dateTime.setDate(dateTime.getDate() + 30000); //30000为当前日期之后多少天
  //   return (
  //     time.getTime() < new Date(startDateTime).getTime() ||
  //     time.getTime() > new Date(endDateTime).getTime()
  //   );
  // },
};
const typeOfDisclosureList = [
  {
    id: "1",
    name: "技术交底",
  },
  {
    id: "2",
    name: "安全交底",
  },
  {
    id: "3",
    name: "质量交底",
  },
  {
    id: "4",
    name: "合同交底",
  },
  {
    id: "5",
    name: "其他",
  },
];
const dredgeServe = {
  //上传图片信息
  HFname: "", //上传图片名称
};

export default {
  name: "ProjectDisclosureAU",
  components: {
    FileUpload,
    sysDialog,
  },
  data() {
    return {
      head: "",
      labelPosition: "right", //表单label位置
      isDisplay: true, //项目基本信息显示状态
      saveForm: Object.assign({}, saveForm), //项目基本信息
      saveRules: Object.assign({}, saveRules), //项目基本信息校验规则
      pickerOptions: Object.assign({}, pickerOptions), //时间选择器
      projectList: [], //项目列表
      typeOfDisclosureList: typeOfDisclosureList, //交底类型列表
      userList: [], //人员列表
      departmentList: [], //被交底部门列表
      HFfileList: [], //上传图片列表
      HFformData: {}, //上传图片数据
      hfpng: "", //上传图片地址
      dredgeServe: Object.assign({}, dredgeServe), //上传图片信息
      isDisplayFile: true, //附件显示状态
      attachments: [], //附件列表
      fileList: [], //附件列表
      config: {}, //配置信息
    };
  },
  watch: {
    //监听 交底人 和 被交底人  不能相同
    "saveForm.objectOfDisclosure"(val) {
      this.saveRules.personBeingDisclosed = [
        {
          validator: (rule, value, callback) => {
            if (value === this.saveForm.objectOfDisclosure) {
              callback(new Error("交底人和被交底人不能相同"));
            } else {
              callback();
            }
          },
          trigger: "change",
        },
      ];
    },
    "saveForm.personBeingDisclosed"(val) {
      this.saveRules.objectOfDisclosure = [
        {
          validator: (rule, value, callback) => {
            if (value === this.saveForm.personBeingDisclosed) {
              callback(new Error("交底人和被交底人不能相同"));
            } else {
              callback();
            }
          },
          trigger: "change",
        },
      ];
    },
  },
  created() {},
  mounted() {
    this.activated(); //获取数据
    this.shezhi(); //设置请求头
    this.fakeData(); //假数据
  },
  methods: {
    fakeData() {
      //假数据
      this.projectList = [
        {
          id: "1",
          name: "项目1",
        },
        {
          id: "2",
          name: "项目2",
        },
        {
          id: "3",
          name: "项目3",
        },
        {
          id: "4",
          name: "项目4",
        },
        {
          id: "5",
          name: "项目5",
        },
      ];
      this.userList = [
        {
          id: "1",
          userName: "张三",
        },
        {
          id: "2",
          userName: "李四",
        },
        {
          id: "3",
          userName: "王五",
        },
        {
          id: "4",
          userName: "赵六",
        },
        {
          id: "5",
          userName: "田七",
        },
      ];
      this.departmentList = [
        {
          id: "1",
          name: "部门1",
        },
        {
          id: "2",
          name: "部门2",
        },
        {
          id: "3",
          name: "部门3",
        },
        {
          id: "4",
          name: "部门4",
        },
        {
          id: "5",
          name: "部门5",
        },
      ];
    },
    shezhi() {
      //设置请求头
      const user = window.sessionStorage.getItem("user");
      const token = user ? JSON.parse(user).token : null;
      let config = {
        Headers: {
          "Content-Type": "application/x-www-form-urlencoded;charset=utf-8", //
          // 设置请求头
          //去除双引号
          Authorization: token ? token.replace(/\"/g, "") : null,
        },
      };
      this.config = config;
    },
    async trueAdd() {
      //文件非空判断
      let d = [];
      let params = JSON.parse(JSON.stringify(this.saveForm));
      if (this.fileList.length != 0) {
        const res = await this.$refs.fileUploadDialog.submit(
          this.fileList,
          "project-disclosure"
        );
        d = res;
        if (d.length == 0) {
          this.$message({
            message: "文件上传失败",
            type: "warning",
          });
          return;
        }
        if (this.$route.params.type === "update") {
          // 循环将文件内容添加到附件id组中 d为附件id组
          for (let i = 0; i < this.attachments.length; i++) {
            d.push(this.attachments[i].id);
          }
        }
        params["fileIds"] = d;
      }
      // 上传图片
      if (this.HFformData) {
        let s = new FormData();
        s.append("file", this.HFformData);
        await axios
          .post("/project-disclosure/uploadImage", s, this.config)
          .then((res) => {
            if (res.data.code == 200) {
              params["scenePicture"] = res.data.data;
            } else {
              return;
            }
          });
      }
      params["applicant"] = JSON.parse(
        window.sessionStorage.getItem("user")
      ).userId;
      request.post("/project-disclosure/save", params).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          // 等待 1.5 秒后返回上一页
          setTimeout(() => {
            this.$router.go(-1);
          }, 1500);
        } else {
          this.$message({
            message: "保存失败",
            type: "warning",
          });
          return;
        }
      });
    },
    deleteFile(index, row) {
      // 删除文件
      if (this.$route.params.type === "update") {
        //  删除数据库中的文件
        let t = [];
        t.push(row.id);
        request.post("/file/deleteFile", { ids: t }).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: "删除成功",
              type: "success",
            });
          } else {
            this.$message({
              message: "删除失败",
              type: "warning",
            });
            return;
          }
        });
      }
      this.fileList.splice(index, 1);
      this.attachments.splice(index, 1);
    },
    handleAdd() {
      // 上传
      this.$refs.fileUploadDialog.show();
    },
    getAttachList(attachments, fileList) {
      //  获取附件信息列表
      this.attachments.push(...attachments);

      // 附件列表
      this.fileList.push(...fileList);
      console.log(this.fileList);
    },
    HFhandleRemove() {
      //删除图片
      this.HFfileList = [];
      this.HFformData = {};
      this.dredgeServe.HFname = "";
      this.hfpng = "";
    },
    HFhandleChangeImg(file, fileList) {
      //上传图片
      //只能上传图片 jpg png 等
      const isPNG =
        file.raw.type === "image/png" ||
        file.raw.type === "image/jpeg" ||
        file.raw.type === "image/jpg" ||
        file.raw.type === "image/gif" ||
        file.raw.type === "image/bmp" ||
        file.raw.type === "image/webp" ||
        file.raw.type === "image/tiff";
      // 图片不能大于 5MB
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (fileList.length > 0) {
        //单个覆盖上传
        this.HFfileList = [fileList[fileList.length - 1]]; // 这一步，是 展示最后一次选择的csv文件
        if (!isPNG) {
          this.$message.error("上传图片格式错误!");
          return false;
        } else if (!isLt2M) {
          this.$message.error("上传图片大小不能超过 5MB!");
          this.HFfileList = [];
          return false;
        } else if (isLt2M && isPNG) {
          this.HFformData = file.raw;
          console.log(this.HFformData);
          this.dredgeServe.HFname = file.name;
        }
        //预览
        var file = file.raw;
        var reader = new FileReader();
        var that = this;
        reader.readAsDataURL(file);
        reader.onload = function (e) {
          that.hfpng = this.result; //上传前可预览图片路径
        };
      }
    },
    async activated() {
      // 获取数据
      if (this.$route.params.type === "add") {
        this.head = "项目交底";
      } else if (this.$route.params.type === "update") {
        this.head = "修改项目";
        // 获取数据
      }
    },
    changeDisplayFile() {
      // 改变附件显示状态
      this.isDisplayFile = !this.isDisplayFile;
    },
    changeDisplay() {
      // 改变项目基本信息显示状态
      this.isDisplay = !this.isDisplay;
    },
    back() {
      //返回上一页
      this.$router.go(-1);
    },
    cellStyle() {
      //表格行居中
      return "text-align:center";
    },
    rowClass() {
      //表格列居中
      return "text-align:center";
    },
  },
};
</script>

<style  scoped>
.container1 {
  overflow-x: initial;
  overflow-y: auto;
  height: 700px;
}
.upload-demo {
  display: flex;
}
</style>